package com.google.gwt.homepage.smile.client.view;


import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler; 
import com.google.gwt.event.dom.client.HasClickHandlers;



import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DecoratorPanel;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.HTMLTable;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.FlexTable.FlexCellFormatter;
import com.google.gwt.user.datepicker.client.DateBox;
import com.google.gwt.user.datepicker.client.DateBox.Format;
import com.google.gwt.homepage.smile.client.presenter.SajuTestPresenter;
import com.google.gwt.homepage.smile.shared.FriendTable;
import com.google.gwt.homepage.smile.shared.SajuDataTable;
import com.google.gwt.homepage.smile.shared.EnneagramTestResultBean;
import com.google.gwt.homepage.smile.shared.SajuData;
import com.google.gwt.i18n.client.Constants;
import com.google.gwt.i18n.client.LocaleInfo;

import com.google.gwt.homepage.smile.shared.EnneagramQuestions;

import java.util.ArrayList;
import java.util.List;

public class SajuTestView extends Composite implements SajuTestPresenter.Display {
  
	
	
	/**
	   * The constants used in this Widget.
	   */
	  
	  public static interface CwConstants extends Constants {
		  
		String sajuTestTitle();
		String sajuTestDesc();
		String[] sajuTimeDatas();
		String[] sajuLandValues();
		String[] sajuSkyValues();
	  }
	
	  private CwConstants constants;
	  
	  
	//private final Button addButton;
  //private final Button deleteButton;
  //private FlexTable contactsTable;
	  private final FlexTable contentTable;//가장 밖 테이블
  private  FlexTable inputSajuTable;
  private  FlexTable resultSajuTable;
  //private  DateBox dateBox;
  private  ListBox yearBox;
  private  ListBox monthBox;
  private  ListBox dateBox;
  private  ListBox timeBox;
  private  Button btnConfirm;
  private  Grid sajuInfo;
  private  FlexTable sajuShortInfo;
  private Button btnSearchFriends;
  //private TextBox yearTxt;
  //private TextBox monthTxt;
  //private TextBox dateTxt;
  private static String loadingImage;
  private HTML loadingImg;
  
  /**
   * The default style name.
   */
  private static final String DEFAULT_STYLE_NAME = "sc-ContentWidget";
	
  
  public SajuTestView(CwConstants constants) {
	  
	  this.constants=constants;
	  
	  
 
	VerticalPanel contentTableDecorator = new VerticalPanel();
    initWidget(contentTableDecorator);
    contentTableDecorator.setWidth("100%");
    
    
    //타이틀, 설명
    contentTable = new FlexTable();
    contentTable.setWidth("100%");
    contentTable.getCellFormatter().addStyleName(0, 0, "contacts-ListContainer");
    contentTable.getCellFormatter().setWidth(0, 0, "100%");
    contentTable.getFlexCellFormatter().setVerticalAlignment(0, 0, DockPanel.ALIGN_TOP);
    
    
    //
    // Create submenu, description
    VerticalPanel widgetVpanel = new VerticalPanel();
    contentTable.setWidget(0, 0, widgetVpanel);

    // Add the name
    HTML nameWidget = new HTML(constants.sajuTestTitle());
    nameWidget.setStyleName(DEFAULT_STYLE_NAME + "-name");
    widgetVpanel.add(nameWidget);

    // Add the description
    //HTML descWidget = new HTML("You can test Enneagram( total 180 question.  It takes about 15minute.)");
    HTML descWidget = new HTML(constants.sajuTestDesc());
    descWidget.setStyleName(DEFAULT_STYLE_NAME + "-description");
    widgetVpanel.add(descWidget);
    
    
    
    //생년월일시 입력부분
    inputSajuTable = new FlexTable();
    inputSajuTable.addStyleName("inputSajuTable");
    
    inputSajuTable.setHTML(0, 0, "생일입력");
    inputSajuTable.getCellFormatter().addStyleName(0, 0, "inputSajuHeader");
    inputSajuTable.setHTML(0, 1, "시간입력");
    inputSajuTable.getCellFormatter().addStyleName(0, 1, "inputSajuHeader");
    btnConfirm = new Button("확인");
    inputSajuTable.setWidget(0, 2, btnConfirm);
    inputSajuTable.getCellFormatter().addStyleName(0, 2, "inputSajuConfirm");
    HorizontalPanel birthPanel = new HorizontalPanel();
    
    birthPanel.add(new Label("양력 "));
    //dateBox = new DateBox();
    //yearTxt = new TextBox();
    //yearTxt.setMaxLength(4);
    //yearTxt.setSize("45px","20px");
    yearBox = new ListBox();
    for (int i = 1881, j=0; i < 2050; i++,j++) {
    	yearBox.addItem(Integer.toString(i));
    	yearBox.setValue(j, Integer.toString(i));
    }
    yearBox.setItemSelected(100, true);//default 1981년 선택
    
    //monthTxt = new TextBox();
    //monthTxt.setMaxLength(2);
    //monthTxt.setSize("25px","20px");
    monthBox = new ListBox();
    for (int i = 1, j=0; i < 13; i++,j++) {
    	monthBox.addItem(Integer.toString(i));
    	monthBox.setValue(j, Integer.toString(i));
    }
    
    //dateTxt = new TextBox();
    //dateTxt.setMaxLength(2);
    //dateTxt.setSize("25px","20px");
    dateBox = new ListBox();
    for (int i = 1, j=0; i < 32; i++,j++) {
    	dateBox.addItem(Integer.toString(i));
    	dateBox.setValue(j, Integer.toString(i));
    }
    
    birthPanel.add(yearBox);
    birthPanel.add(new HTML("년 "));
    birthPanel.add(monthBox);
    birthPanel.add(new HTML("월 "));
    birthPanel.add(dateBox);
    birthPanel.add(new HTML("일"));
    
    inputSajuTable.setWidget(1, 0, birthPanel);
    inputSajuTable.getCellFormatter().addStyleName(1, 0, "inputSajuBirth");
    
    timeBox = new ListBox();
    String[] listTypes = constants.sajuTimeDatas();
    for (int i = 0; i < listTypes.length; i++) {
    	timeBox.addItem(listTypes[i]);
    	timeBox.setValue(i, Integer.toString(i));//값을 0~11로 설정(23~1시(0), 1~3시(1)...)
    }
    inputSajuTable.setWidget(1, 1, timeBox);
    inputSajuTable.getCellFormatter().addStyleName(1, 1, "inputSajuTime");
    FlexCellFormatter cellFormatter = inputSajuTable.getFlexCellFormatter();
    cellFormatter.setRowSpan(0, 2, 2);
    
    

    //사주결과
    resultSajuTable = new FlexTable();
    resultSajuTable.addStyleName("resultSajuTable");

    resultSajuTable.setVisible(false);//처음에 않보이게
    
    sajuInfo = new Grid(4,3);
    sajuInfo.addStyleName("sajuInfo");
    /*
    sajuInfo.setHTML(0, 0, "신유");
    sajuInfo.setHTML(0, 1, "金金");
    sajuInfo.setHTML(0, 2, "--");
    
    sajuInfo.setHTML(1, 0, "경인");
    sajuInfo.setHTML(1, 1, "金木");
    sajuInfo.setHTML(1, 2, "+-");
    
    sajuInfo.setHTML(2, 0, "기해");
    sajuInfo.setHTML(2, 1, "土木");
    sajuInfo.setHTML(2, 2, "-+");
    
    sajuInfo.setHTML(3, 0, "계묘");
    sajuInfo.setHTML(3, 1, "水木");
    sajuInfo.setHTML(3, 2, "--");
    */
    
    sajuShortInfo = new FlexTable();
    sajuShortInfo.addStyleName("sajuShortInfo");
    
    sajuShortInfo.setHTML(0, 0, "&nbsp");
    sajuShortInfo.getCellFormatter().setStyleName(0, 0, "ohangCnt");
    sajuShortInfo.setHTML(0, 1, "&nbsp");
    sajuShortInfo.getCellFormatter().setStyleName(0, 1, "percent");
    sajuShortInfo.setHTML(1, 0, "&nbsp");
    sajuShortInfo.getCellFormatter().setStyleName(1, 0, "yoyak");
    cellFormatter = sajuShortInfo.getFlexCellFormatter();
    cellFormatter.setRowSpan(0, 0, 2);
    
    
    btnSearchFriends = new Button("친구 찾기");
    
    resultSajuTable.setWidget(0, 0, sajuInfo);
    resultSajuTable.setWidget(0, 1, sajuShortInfo);
    resultSajuTable.getCellFormatter().setStyleName(0, 1, "resultSajuZeroOne");//오른쪽 정렬을 위해
    //친구찾기
    //resultSajuTable.setWidget(1, 0, new HTML("&nbsp;"));
    //resultSajuTable.setWidget(1, 1, btnSearchFriends);
    //resultSajuTable.getCellFormatter().setStyleName(1, 1, "resultSajuRightAlign");//오른쪽 정렬을 위해
    
    
    
    
    
    
    
    
    //VerticalPanel contentsPanel= new  VerticalPanel();
    //contentsPanel.add(inputSajuTable);
    
    
    
    // Show the loading image
    if (loadingImage == null) {
      loadingImage = "<img src=\"" + GWT.getModuleBaseURL()
          + "images/loading.gif\">";
    }
    
    loadingImg = new HTML(loadingImage);
    loadingImg.setVisible(false);
    
    
    contentTable.setWidget(1, 0, inputSajuTable);//생년월일 입력부분
    contentTable.setWidget(2, 0, resultSajuTable);//사주 결과부분

    contentTable.setWidget(3, 0, loadingImg);//사주 결과부분
    
    contentTableDecorator.add(contentTable);
    
    
    
    
 
/*
    contentTable = new FlexTable();
    contentTable.setWidth("100%");
    contentTable.getCellFormatter().addStyleName(0, 0, "contacts-ListContainer");
    contentTable.getCellFormatter().setWidth(0, 0, "100%");
    contentTable.getFlexCellFormatter().setVerticalAlignment(0, 0, DockPanel.ALIGN_TOP);

    VerticalPanel widgetVpanel = new VerticalPanel();
    contentTable.setWidget(0, 0, widgetVpanel);

 
    HTML nameWidget = new HTML(constants.enneagramTestTitle());
    nameWidget.setStyleName(DEFAULT_STYLE_NAME + "-name");
    widgetVpanel.add(nameWidget);

 
    HTML descWidget = new HTML(constants.enneagramTestDesc());
    descWidget.setStyleName(DEFAULT_STYLE_NAME + "-description");
    widgetVpanel.add(descWidget);
    

    contentArea= new SimplePanel();
    contentTable.setWidget(1, 0, contentArea);
    contentTableDecorator.add(contentTable);
*/   
  }
  
  
  
  
  
  /*
  public HasClickHandlers getAddButton() {
    return addButton;
  }
  
  public HasClickHandlers getDeleteButton() {
    return deleteButton;
  }
  
  public HasClickHandlers getList() {
    return contactsTable;
  }

  public void setData(List<String> data) {
    contactsTable.removeAllRows();
    
    for (int i = 0; i < data.size(); ++i) {
      contactsTable.setWidget(i, 0, new CheckBox());
      contactsTable.setText(i, 1, data.get(i));
    }
  }
  
  public int getClickedRow(ClickEvent event) {
    int selectedRow = -1;
    HTMLTable.Cell cell = contactsTable.getCellForEvent(event);
    
    if (cell != null) {
      // Suppress clicks if the user is actually selecting the 
      //  check box
      //
      if (cell.getCellIndex() > 0) {
        selectedRow = cell.getRowIndex();
      }
    }
    
    return selectedRow;
  }
  
  public List<Integer> getSelectedRows() {
    List<Integer> selectedRows = new ArrayList<Integer>();
    
    for (int i = 0; i < contactsTable.getRowCount(); ++i) {
      CheckBox checkBox = (CheckBox)contactsTable.getWidget(i, 0);
      if (checkBox.getValue()) {
        selectedRows.add(i);
      }
    }
    
    return selectedRows;
  }
  */
  
 
  
  public HasClickHandlers getSajuResultButton(){
	  return btnConfirm;
  }
  public String getInputedYear(){
	  return yearBox.getValue(yearBox.getSelectedIndex());
  }
  public String getInputedMonth(){
	  return monthBox.getValue(monthBox.getSelectedIndex());
  }
  public String getInputedDate(){
	  return dateBox.getValue(dateBox.getSelectedIndex());
  }
  public String getInputedTiem(){
	  return timeBox.getValue(timeBox.getSelectedIndex());  
  }
  public void setSajuResult(SajuDataTable result){
	  
	  //기존데이터 삭제
	  //to do
	  
	  
	  //사주팔자 
	  sajuInfo.setText(0, 0, result.getYearSkyVal()+result.getYearLandVal());
	  sajuInfo.setText(1, 0, result.getMonthSkyVal()+result.getMonthLandVal());
	  sajuInfo.setText(2, 0, result.getDateSkyVal()+result.getDateLandVal());
	  sajuInfo.setText(3, 0, result.getTimeSkyVal()+result.getTimeLandVal());
	  
	  
	  //오행
	  sajuInfo.setText(0, 1, result.getYearSky5hang()+result.getYearLand5hang());
	  sajuInfo.setText(1, 1, result.getMonthSky5hang()+result.getMonthLand5hang());
	  sajuInfo.setText(2, 1, result.getDateSky5hang()+result.getDateLand5hang());
	  sajuInfo.setText(3, 1, result.getTimeSky5hang()+result.getTimeLand5hang());
	  
	  // +, -
	  sajuInfo.setText(0, 2, result.getYearSkyPM()+result.getYearLandPM());
	  sajuInfo.setText(1, 2, result.getMonthSkyPM()+result.getMonthLandPM());
	  sajuInfo.setText(2, 2, result.getDateSkyPM()+result.getDateLandPM());
	  sajuInfo.setText(3, 2, result.getTimeSkyPM()+result.getTimeLandPM());
	  
	  //오행 갯수
	  int[] onhangCnt = result.getOhhangCnt();
	  sajuShortInfo.setHTML(0, 0, "木 "+onhangCnt[0]+"<br>"+"火 "+onhangCnt[1]+"<br>"+"土 "+onhangCnt[2]+"<br>"+"金 "+onhangCnt[3]+"<br>"+"水 "+onhangCnt[4]);
	  
	  //음양 비율
	  sajuShortInfo.setText(0, 1, "음 "+result.getMinusPercent()+" 양 "+result.getPlusPercent());
	  
	  //간단한 설명
	  sajuShortInfo.setText(1, 0, result.getYoyakDesc());
	  
	  
	  
	  //로딩 이미지 보이지 않게
	  loadingImg.setVisible(false);
	  
	  //결과가 보이게 설정
	  resultSajuTable.setVisible(true);
	  
  }

  public void invisibleSajuResult(){
	  resultSajuTable.setVisible(false);
  }
  
  
  public void setLoadImg(){//로드 이미지 설정
	  loadingImg.setVisible(true);
  }
  
  

  public HasClickHandlers getSearchFriendButton(){
	  return btnSearchFriends;
  }

  
  
//결과창 보여줌
  public void showSearchFriendResult(List<FriendTable> result){
	 
  		DialogBox dialogBox =  createDialogBox(result);
  		//System.out.println("333");
		dialogBox.setAnimationEnabled(true);
		dialogBox.setGlassEnabled(true);
		dialogBox.center();
        dialogBox.show();
  }  
  
  
  
  /**
   * 테스트 결과를 보여준다.
   *
   * @return the new dialog box
   */
  private DialogBox createDialogBox(List<FriendTable> result) {
	  
	  

    
    final DialogBox dialogBox = new DialogBox();
    //dialogBox.ensureDebugId("cwDialogBox");
    
    
    
    
    dialogBox.setText("친구 찾기");
   
    //dialogBox.setPixelSize(250, 70);
    
    // Create a table to layout the content
    VerticalPanel dialogContents = new VerticalPanel();
    dialogContents.setSpacing(5);
    dialogBox.setWidget(dialogContents);

    
    ////////////////////////////////////////////
    /*
    Grid grid = new Grid(result.getQuestionNumForType()+1, 10);
    for(int i=1;i<=9;i++){
    	 grid.setWidget(0, i, new HTML(i+"유형"));
    }
    
    for(int i=1;i<=result.getQuestionNumForType();i++){
   	 grid.setWidget(i, 0, new HTML(Integer.toString(i)+"번"));
   }
   
    
    for(int i=1;i<=result.getQuestionNumForType();i++){
    	for(int j=1;j<=9;j++){
    		String resultTxt="";
    		if(result.isSelectedAgree(j,i)){
    			resultTxt="동의";
    		}else if(result.isSelectedMedi(j,i)){
    			resultTxt="보통";
    		}else if(result.isSelectedRej(j,i)){
    			resultTxt="반대";
    		}
    		grid.setWidget(i, j, new HTML(resultTxt));
    	}
    }
    dialogContents.add(grid);
    dialogContents.setCellHorizontalAlignment(
    		grid, HasHorizontalAlignment.ALIGN_CENTER);
   */
  ////////////////////////////////////////////////////////////
   
    
    // Create a grid
    FlexTable searchFriendTable = new FlexTable();
    
    
    searchFriendTable.setWidget(0, 0, new HTML("순위"));
    searchFriendTable.setWidget(0, 1, new HTML("이름"));
    searchFriendTable.setWidget(0, 2, new HTML("점수"));
    searchFriendTable.setWidget(0, 3, new HTML("자기소개"));
    searchFriendTable.setWidget(0, 4, new HTML("채팅"));
    searchFriendTable.setWidget(0, 5, new HTML("이메일"));
    searchFriendTable.setWidget(0, 6, new HTML("사는곳"));
    
    
    for (int i=0; i < result.size() && i<10 ;i++) {
    	FriendTable friend=result.get(i);
    	searchFriendTable.setWidget(i+1, 0, new HTML(Integer.toString(i+1)));
    	searchFriendTable.setWidget(i+1, 1, new HTML(friend.getFriend_email()));
    	searchFriendTable.setWidget(i+1, 2, new HTML(Integer.toString(friend.getScore())));
    	searchFriendTable.setWidget(i+1, 3, new Button("자기소개"));
    	searchFriendTable.setWidget(i+1, 4, new Button("채팅하기"));
    	searchFriendTable.setWidget(i+1, 5, new Button("이메일 보내기"));
    	searchFriendTable.setWidget(i+1, 6, new HTML("서울시 용산구"));
    }
    
    searchFriendTable.addStyleName("searchFriendTable");
    searchFriendTable.getRowFormatter().addStyleName(0, "title");
    
   
    
    ////////////////////////////////
  
    dialogContents.add(searchFriendTable);
    ////////////////////////////////
    
    
    

 
    
    //System.out.println("555");
    // Add a close button at the bottom of the dialog
    Button closeButton = new Button(
        "닫기", new ClickHandler() {
          public void onClick(ClickEvent event) {
            dialogBox.hide();
          }
        });
    dialogContents.add(closeButton);
    
    if (LocaleInfo.getCurrentLocale().isRTL()) {
      dialogContents.setCellHorizontalAlignment(
          closeButton, HasHorizontalAlignment.ALIGN_LEFT);

    } else {
      dialogContents.setCellHorizontalAlignment(
          closeButton, HasHorizontalAlignment.ALIGN_RIGHT);
    }
	
    // Return the dialog box
    return dialogBox;
  }
  
  
  
  
  public Widget asWidget() {
    return this;
  }
}
